"""
自动迁移脚本 - 一键完成数据库设置和数据迁移
"""

import os
import sys
import asyncio
import json
from pathlib import Path

# 添加当前目录到路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

async def main():
    print("=== MindMate 自动迁移工具 ===")
    
    # 设置环境变量（从配置文件读取的值）
    os.environ['SUPABASE_URL'] = 'https://wfmarihxfyyqljzaakbk.supabase.co'
    os.environ['SUPABASE_ANON_KEY'] = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6IndmbWFyaWh4Znl5cWxqemFha2JrIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTcxNTM5MDQsImV4cCI6MjA3MjcyOTkwNH0.9KoJUGhMbMNyNZhFHaqUIv3mt4z26XnbN4sMq0XlUxo'
    
    print("1. 检查现有数据...")
    
    # 检查现有数据
    data_dir = Path("./data")
    sessions_file = data_dir / "sessions.json"
    roles_file = data_dir / "roles.json"
    
    sessions_count = 0
    roles_count = 0  
    messages_count = 0
    
    if sessions_file.exists():
        with open(sessions_file, 'r', encoding='utf-8') as f:
            sessions = json.load(f)
        sessions_count = len(sessions)
        for session in sessions.values():
            messages_count += len(session.get('messages', []))
    
    if roles_file.exists():
        with open(roles_file, 'r', encoding='utf-8') as f:
            roles = json.load(f)
        roles_count = len(roles)
    
    print(f"发现数据: {sessions_count} 个会话, {roles_count} 个角色, {messages_count} 条消息")
    
    if sessions_count == 0 and roles_count == 0:
        print("没有找到数据，无需迁移")
        return
    
    print("\\n2. 测试数据库连接...")
    
    try:
        from database.supabase_client import check_supabase_config, test_connection, get_supabase_client
        
        if not check_supabase_config():
            print("[ERROR] 配置检查失败")
            return
            
        print("[OK] 配置检查通过")
        
        if not test_connection():
            print("[ERROR] 数据库连接失败")
            return
            
        print("[OK] 数据库连接成功")
        
    except Exception as e:
        print(f"[ERROR] 连接测试失败: {e}")
        return
    
    print("\\n3. 创建数据库表结构...")
    
    try:
        # 使用Supabase客户端执行SQL
        supabase = get_supabase_client()
        
        # 读取并执行SQL脚本
        init_sql_path = Path("database/init.sql")
        if not init_sql_path.exists():
            print("[ERROR] 未找到 init.sql 文件")
            return
            
        with open(init_sql_path, 'r', encoding='utf-8') as f:
            sql_content = f.read()
        
        # 分割SQL语句并逐个执行
        sql_statements = []
        current_statement = ""
        
        for line in sql_content.split('\\n'):
            line = line.strip()
            if line and not line.startswith('--'):
                current_statement += line + " "
                if line.endswith(';'):
                    sql_statements.append(current_statement.strip())
                    current_statement = ""
        
        print(f"准备执行 {len(sql_statements)} 条SQL语句...")
        
        executed = 0
        for sql in sql_statements:
            if sql and len(sql) > 5:  # 跳过太短的语句
                try:
                    result = supabase.rpc('exec_sql', {'sql': sql}).execute()
                    executed += 1
                except Exception as e:
                    # 尝试直接执行（某些语句可能不支持rpc方式）
                    if "CREATE TABLE" in sql or "CREATE INDEX" in sql:
                        print(f"[WARN] 跳过语句: {sql[:50]}...")
                    else:
                        print(f"[ERROR] 执行SQL失败: {e}")
        
        print(f"[OK] 已尝试执行 {executed} 条SQL语句")
        
        # 手动创建关键表（如果rpc方式失败）
        try:
            # 检查表是否存在，如果不存在则提示手动创建
            result = supabase.table('sessions').select('count', count='exact').limit(1).execute()
            print("[OK] sessions表已存在")
        except:
            print("[WARN] 无法通过API创建表结构，需要手动在Supabase SQL编辑器中执行init.sql")
            print("请访问: https://wfmarihxfyyqljzaakbk.supabase.co")
            print("在SQL Editor中执行 database/init.sql 的内容")
            input("执行完成后按回车继续...")
        
    except Exception as e:
        print(f"[ERROR] 创建表结构失败: {e}")
        print("\\n请手动在Supabase中创建表结构:")
        print("1. 访问 https://wfmarihxfyyqljzaakbk.supabase.co")
        print("2. 进入 SQL Editor")
        print("3. 执行 database/init.sql 中的SQL脚本")
        input("完成后按回车继续...")
    
    print("\\n4. 开始数据迁移...")
    
    try:
        from migrate_to_database import DataMigrator
        
        migrator = DataMigrator(str(data_dir), force=False)
        success = await migrator.migrate()
        
        if success:
            print("[SUCCESS] 数据迁移完成!")
            print("\\n迁移统计:")
            print(f"会话: {migrator.stats['sessions_migrated']} 个")
            print(f"消息: {migrator.stats['messages_migrated']} 条")
            print(f"角色: {migrator.stats['roles_migrated']} 个")
            
            if migrator.stats['sessions_skipped'] > 0:
                print(f"跳过会话: {migrator.stats['sessions_skipped']} 个 (已存在)")
            if migrator.stats['roles_skipped'] > 0:
                print(f"跳过角色: {migrator.stats['roles_skipped']} 个 (已存在)")
            
            if migrator.stats['errors']:
                print(f"\\n遇到 {len(migrator.stats['errors'])} 个错误:")
                for error in migrator.stats['errors'][:3]:
                    print(f"  - {error}")
        else:
            print("[ERROR] 数据迁移失败")
            
    except Exception as e:
        print(f"[ERROR] 迁移过程出错: {e}")
        import traceback
        traceback.print_exc()
    
    print("\\n5. 迁移完成!")
    print("你的数据现在已经安全存储在Supabase云数据库中")
    print("可以在以下地址查看:")
    print("https://wfmarihxfyyqljzaakbk.supabase.co")

if __name__ == "__main__":
    asyncio.run(main())